<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 角色列表 -->
      <el-button type="primary" @click="addinfo">添加角色</el-button>
      <!-- 弹框 -->
      <el-dialog :title="title" :visible.sync="dialogFormVisibleAdd">
        <el-form
          :model="form"
          :rules="rules"
          ref="form"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item
            label="角色名称"
            prop="roleName"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.roleName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="角色描述"
            prop="roleDesc"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.roleDesc" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="quXiao" :plain="true">取 消</el-button>
          <el-button type="primary" @click="yes">确 定</el-button>
        </div>
      </el-dialog>
      <template>
        <div class="table">
          <el-table
            :data="roleList"
            border
            style="width: 100%"
            :row-class-name="tableRowClassName"
          >
            <el-table-column type="index" label=""> </el-table-column>
            <el-table-column
              v-for="(item, index) in columnData"
              :key="index"
              :prop="item.prop"
              :label="item.label"
            ></el-table-column>
            <el-table-column prop="address" label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editData(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteData(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </el-card>
  </div>
</template>

<script>
// 引入lodash防抖
import { debounce } from 'lodash'
export default {
  data() {
    return {
      isEdit: false,
      editId: '',
      dialogFormVisibleAdd: false,
      title: '',
      form: {
        roleName: '',
        roleDesc: '',
      },
      formLabelWidth: '120px',
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
      },
      columnData: [
        {
          prop: 'roleName',
          label: '角色名称',
        },
        {
          prop: 'roleDesc',
          label: '角色描述',
        },
      ],
      roleList: [],
    }
  },
  methods: {
    // 获取数据
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.roleList = res.data
    },
    // 添加到后台
    async postRolesList() {
      const { data: res } = await this.$http.post('roles', this.form)
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
    },
    // 编辑方法
    async putRolesList() {
      const { data: res } = await this.$http.put(
        `roles/${this.editId}`,
        this.form
      )
      this.getRolesList()
    },
    // 表格隔行变色
    tableRowClassName({ rowIndex }) {
      return rowIndex % 2 == 0 ? 'warning-row' : 'success-row'
    },
    // 编辑
    editData(row) {
      this.isEdit = true
      this.title = '编辑角色'
      this.dialogFormVisibleAdd = true
      this.form.roleName = row.roleName
      this.form.roleDesc = row.roleDesc
      this.editId = row.id
    },
    // 删除
    deleteData(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$http.delete(`roles/${row.id}`).then((res) => {
            if (res.data.meta.status !== 200)
              return this.$message.error(res.data.meta.msg)
            console.log(res)
            this.$message({
              type: 'success',
              message: '删除成功!',
            })
            this.getRolesList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    //点击 添加
    addinfo() {
      this.title = '添加角色'
      this.isEdit = false
      this.dialogFormVisibleAdd = true
      this.form.roleDesc = ''
      this.form.roleName = ''
    },
    // 取消
    quXiao() {
      this.dialogFormVisibleAdd = false
      this.$message({
        showClose: true,
        message: '已取消',
      })
    },

    // 弹窗确定按钮
    // 使用 Lodash 的 debounce 函数来实现防抖
    yes: debounce(function () {
      if (this.isEdit) {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            this.$message.error('编辑失败，内容不符合要求')
            return false
          }
          this.putRolesList()
          this.dialogFormVisibleAdd = false
        })
      } else {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            this.$message.error('添加失败，内容不符合要求')
            return false
          }
          this.postRolesList()
          this.dialogFormVisibleAdd = false
        })
      }
    }, 200),
  },
  created() {
    this.getRolesList()
  },
}
</script>

<style lang="less" scoped>
.table ::v-deep.el-table .warning-row {
  background: #fff;
}

.table ::v-deep.el-table .success-row {
  background: #fafafa;
}
</style>
